package com.winit.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.beans.LoginUser;
import com.winit.common.util.Constants;
import com.winit.common.util.HttpClientUtil;
import com.winit.common.util.ObjectToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangjian on 16/1/16.
 */
public class UserInfoUtil {
    static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class);

    public static LoginUser getUserInfo(HttpServletRequest request){
        String tokenId = request.getParameter("tokenId");

        if(StringUtils.isEmpty(tokenId)){
            logger.info("获取用户信息失败,tokenId=null");
            return null;
        }
        LoginUser userInfo = null;
        try {
            JSONObject jsonObject = HttpClientUtil.doGetForJson(Constants.BEETLE_AUTH_URL+"/login/info?token_id="+tokenId);
            if(jsonObject.getBoolean("success")){
                userInfo = JSONObject.toJavaObject(jsonObject.getJSONObject("data"),LoginUser.class);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.filter.UserInfoUtil.getUserInfo 异常",e);
        }

        if(userInfo == null || StringUtils.isEmpty(userInfo.getUserName()) || userInfo.getUserRole().size() == 0){
            logger.info("获取用户信息失败,tokenId="+tokenId+",userInfo=null");
            return null;
        }

        logger.info("获取用户信息成功,tokenId="+tokenId+",userInfo="+ObjectToString.getString(userInfo));
        userInfo.setTokenId(tokenId);
        return userInfo;
    }
}
